# chat1
# originally from 
# http://homepages.ius.edu/rwisman/b438/Html/UDPProgrammingExercise.htm
# modified slightly by Joel R. Voss
# Jan 19, 2006

from socket import *
import threading

class receiver(threading.Thread):  # Receiver thread
	def __init__(self, socket):
		threading.Thread.__init__(self)
		self.SOCKET=socket
		self.setDaemon(True) # Daemon threads stop with main thread
	#end def __init_(socket)
	
	def run(self):
		while True: # Receive in daemon thread
			data, address = self.SOCKET.recvfrom(1024)
			if not data: break
			print address, ' ', data
		self.SOCKET.close()
	#end def run()
   
#end class receiver(threading.Thread)

def main(toName='localhost', ioPort=3111, receiverPort=3222):
	ioSocket=socket(AF_INET, SOCK_DGRAM)
	#ioPort = 3111
	#receiverPort=ioPort
	#toName = 'dmitry.altsci.com'
	
	#if toName == 'dmitry.altsci.com': 
	#receiverPort = 3222
	
	#try :
	ioSocket.bind(('',ioPort))
	#except Exception, msg :
	#	ioPort = 3222
	#	receiverPort = 3111
	#	ioSocket.bind(('',ioPort))
	#end try
	
	print 'chat1 on port ', ioPort, '. Blank line to quit.'
	
	receiver(ioSocket).start()              # Create receiver thread and start
	
	while True :                                 # Send in main thread
		userIn = raw_input()
		if not userIn : break
		ioSocket.sendto(userIn, (toName, receiverPort))
	#loop
	
	ioSocket.close()
#end def main()

if __name__ == '__main__':
	from sys import argv
	if len(argv) > 1:
		HOST = argv[1]
	else:
		HOST = 'localhost'    # The remote host
	#end if
	if len(argv) > 2:
		PORT1 = int(argv[2])
	else:
		PORT1 = 3111          # The send port
	#end if
	if len(argv) > 3:
		PORT2 = int(argv[3])
	else:
		PORT2 = 3222          # The receive port
	#end if
	main(HOST, PORT1, PORT2)
#end if

